package com.cskaoyan.service.impl;

import com.cskaoyan.bean.bo.*;
import com.cskaoyan.bean.param.BaseParam;
import com.cskaoyan.bean.pojo.*;
import com.cskaoyan.bean.vo.*;
import com.cskaoyan.mapper.*;
import com.cskaoyan.service.SystemService;
import com.cskaoyan.util.Constant;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author :beauty
 * @version : $version
 * @date :Created in 2022/4/6   17:15
 * @description:
 * @return:
 */
@Service
public class SystemServiceImpl implements SystemService {

    @Autowired
    MarketAdminMapper marketAdminMapper;

    @Autowired
    MarketStorageMapper marketStorageMapper;


    @Override
    public AdminAdminListVo query(AdminListBo adminListBo) {
        Integer page = adminListBo.getPage();//页码
        Integer limit = adminListBo.getLimit();//数据量
        String sort = adminListBo.getSort();//排序列
        String order = adminListBo.getOrder();//desc\asc
        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(page, limit);
        //执行查询过程中拼接分页信息
        MarketAdminExample marketAdminExample = new MarketAdminExample();
        MarketAdminExample.Criteria criteria = marketAdminExample.createCriteria();
        if (adminListBo.getUsername() != null && !"".equals(adminListBo.getUsername())) {
            criteria.andUsernameLike("%" + adminListBo.getUsername()+"%");
        }
        criteria.andDeletedEqualTo(false);
        marketAdminExample.setOrderByClause(sort+" "+order);
        List<MarketAdmin> admins = marketAdminMapper.selectByExample(marketAdminExample);
        List<AdminAdminInnerAdmin> innerAdmins = new ArrayList<>();
        for (MarketAdmin admin : admins) {
            //此处需要将String转换为int[]

            AdminAdminInnerAdmin adminInnerAdmin =
                    new AdminAdminInnerAdmin(admin.getId(),admin.getUsername(),
                            ""+admin.getAvatar(),admin.getRoleIds());
            innerAdmins.add(adminInnerAdmin);
        }
        PageInfo<MarketAdmin> pageInfo = new PageInfo<>(admins);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        return AdminAdminListVo.data(total,pages,limit,page,innerAdmins);
    }

    @Override
    public MarketAdmin insert(AdminCreateBo adminCreateBo) {
        MarketAdmin marketAdmin = new MarketAdmin(null,
                adminCreateBo.getUsername(),adminCreateBo.getPassword(),
                null,null,adminCreateBo.getAvatar(),new Date(),new Date(),
                false,adminCreateBo.getRoleIds());
         marketAdminMapper.insertSelective(marketAdmin);

        return marketAdmin;
    }


//    @Override
//    public AdminCreatePicStoreVo addPic(String filename, String contentType, long size,String url) {
//        //生成uuid作为储存文件（图片）的key
//        String randomName = UUID.randomUUID().toString().trim().replaceAll("-","");
//        String key=randomName+"."+contentType;
//        //生成文件对象
//        MarketStorage marketStorage = new MarketStorage(null,key,filename,
//                contentType, ((int) size),url,new Date(),new Date(),false);
//        //文件对象存入数据库
//        marketStorageMapper.insertSelective(marketStorage);
//        AdminCreatePicStoreVo adminCreatePicStoreVo = new AdminCreatePicStoreVo(null,
//                key,filename,contentType, ((int) size),url,new Date().toString()
//                ,new Date().toString());
//        return adminCreatePicStoreVo;
//    }

    @Override
    public AdminUpdateVo adminUpdate(AdminCreateBo adminCreateBo) {
        String loginIp = Constant.domain;
        MarketAdmin marketAdmin = new MarketAdmin(adminCreateBo.getId(),
                adminCreateBo.getUsername(), adminCreateBo.getPassword(), loginIp, new Date(),
                adminCreateBo.getAvatar(), new Date(), new Date(), false, adminCreateBo.getRoleIds());

        marketAdminMapper.updateByPrimaryKey(marketAdmin);
        AdminUpdateVo adminUpdateVo = new AdminUpdateVo(adminCreateBo.getId(),
                adminCreateBo.getUsername(),adminCreateBo.getAvatar(),new Date().toString(),
                adminCreateBo.getRoleIds());
        return adminUpdateVo;
    }

    @Override
    public void delete(AdminCreateBo adminCreateBo) {
        MarketAdmin marketAdmin = marketAdminMapper.selectByPrimaryKey(adminCreateBo.getId());
        marketAdmin.setDeleted(true);
        marketAdminMapper.updateByPrimaryKey(marketAdmin);
    }

    @Autowired
    MarketLogMapper marketLogMapper;
    @Override
    public AdminLogListVo queryLog(AdminLogListBo logListBo) {
        Integer page = logListBo.getPage();//页码
        Integer limit = logListBo.getLimit();//数据量
        String sort = logListBo.getSort();//排序列
        String order = logListBo.getOrder();//desc\asc
        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(page, limit);
        //执行查询过程中拼接分页信息
        MarketLogExample example = new MarketLogExample();
        MarketLogExample.Criteria criteria = example.createCriteria();
        if (logListBo.getName() != null && !"".equals(logListBo.getName())) {
            criteria.andAdminLike("%" +logListBo.getName()+ "%");
        }
        criteria.andDeletedEqualTo(false);
        example.setOrderByClause(sort+" "+order);
        List<MarketLog> logList = marketLogMapper.selectByExample(example);
        PageInfo<MarketLog> pageInfo = new PageInfo<>(logList);
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();

        return new AdminLogListVo(((int) total),pages,limit,page,logList);
    }


    @Transactional
    @Override
    public MarketStorage storageCreate(MultipartFile file, String finalFileName, String relativePath) {
        String originalFilename = file.getOriginalFilename();   // 图片的原始名字：name
        String contentType = file.getContentType();    // 图片类型：image/jpeg
        Long longSize = file.getSize();     // 图片大小
        int size = longSize.intValue();
        MarketStorage marketStorage = new MarketStorage(null, finalFileName, originalFilename, contentType,
                size, relativePath, new Date(), new Date(), false);
        // 将图片插入数据库
        marketStorageMapper.insert(marketStorage);
        // 根据图片的finalFileName，就是key，取出图片信息
        List<MarketStorage> marketStorages = marketStorageMapper.selectByKey(finalFileName);
        // 拼接url
        MarketStorage storage = marketStorages.get(0);
        String url = storage.getUrl();
        storage.setUrl(Constant.domain + "/" + url);

        return storage;
    }


    @Override
    public StorageListVo storageList(BaseParam baseParam,String key,String name) {

        /*Integer page = baseParam.getPage();//页码
        Integer limit = baseParam.getLimit();//数据量
        String sort = baseParam.getSort();//排序列
        String order = baseParam.getOrder();//desc\asc
        //分页插件 PageHelper，辅助我们做分页以及分页信息的获得
        PageHelper.startPage(page, limit);
        //执行查询过程中拼接分页信息
        MarketStorageExample example = new MarketStorageExample();
        example.setOrderByClause(sort+" "+order);
        List<MarketStorage> storageList = marketStorageMapper.selectByExample(example);*/
        //唐学成更新版
        Integer page = baseParam.getPage();
        Integer limit = baseParam.getLimit();
        String sort = baseParam.getSort();
        String order = baseParam.getOrder();
        PageHelper.startPage(page,limit);
        MarketStorageExample marketStorageExample = new MarketStorageExample();
        marketStorageExample.setOrderByClause(sort + " " + order);
        MarketStorageExample.Criteria criteria = marketStorageExample.createCriteria();
        //deleted = false,key,name
        if (key != null &&! "".equals(key)) {
            criteria.andKeyEqualTo(key);
        }
        if (name != null && !"".equals(name)) {
            criteria.andNameLike("%" + name + "%");
        }
        criteria.andDeletedEqualTo(false);
        List<MarketStorage> marketStorages = marketStorageMapper.selectByExample(marketStorageExample);
        PageInfo<MarketStorage> pageInfo = new PageInfo<>(marketStorages);
        for (MarketStorage marketStorage : marketStorages) {
            String url = marketStorage.getUrl();
            if (!url.equals(Constant.domain)) {
                marketStorage.setUrl(Constant.domain+"/"+url);
            }
        }
        long total = pageInfo.getTotal();
        int pages = pageInfo.getPages();
        StorageListVo storageListVo = new StorageListVo((int) total, pages, limit, page, marketStorages);
        /*PageInfo<MarketStorage> marketStoragePageInfo = new PageInfo<>(storageList);
       List<StorageListVoInner> listVoInners = new ArrayList<>();
        for (MarketStorage marketStorage : storageList) {
            String addTime = marketStorage.getAddTime().toString();
            String updateTime = marketStorage.getUpdateTime().toString();
            StorageListVoInner listVoInner = new StorageListVoInner(marketStorage.getId(), marketStorage.getKey(),
                    marketStorage.getName(), marketStorage.getType(), marketStorage.getSize(), marketStorage.getUrl(),
                    addTime, updateTime, marketStorage.getDeleted());
            listVoInners.add(listVoInner);
        }
        int pages = marketStoragePageInfo.getPages();
        int total = (int) marketStoragePageInfo.getTotal();
        StorageListVo storageListVo = new StorageListVo(total, pages, limit, page, listVoInners);*/
        return storageListVo;
    }

    @Override
    public MarketStorage updateStorage(MarketStorage marketStorage) {
        marketStorageMapper.updateByPrimaryKey(marketStorage);
        return marketStorage;
    }

    @Override
    public void deleteStorage(MarketStorage marketStorage) {
        marketStorage.setDeleted(true);
        marketStorageMapper.updateByPrimaryKey(marketStorage);
    }

    /**
     * 角色管理模块
     */
    @Autowired
    MarketRoleMapper marketRoleMapper;

    @Autowired
    RolePermissionsRelationMapper rolePermissionsRelationMapper;

    @Autowired
    RolePermissionsMapper rolePermissionsMapper;

    @Override
    public RoleOptionVo queryAllRole() {
        //查找所有角色需要改！没有页面参数怎么办？
        //不需要页面参数都是在一个可以滑动的下拉窗口里面

        List<RoleOptionVoInnerList> marketRoleList = marketRoleMapper.selectAllRoles();
        PageInfo<RoleOptionVoInnerList> rolePageInfo = new PageInfo<>(marketRoleList);
        int total = (int) rolePageInfo.getTotal();
        int pages = rolePageInfo.getPages();
        int size = marketRoleList.size();
        return new RoleOptionVo(total, pages, size, 1, marketRoleList);

    }

    @Override
    public RoleListVo queryAllRoleList(RoleListBo roleListBo) {
        Integer page = roleListBo.getPage();//页码
        Integer limit = roleListBo.getLimit();//数据量
        String sort = roleListBo.getSort();//排序
        String order = roleListBo.getOrder();//排序顺序
        PageHelper.startPage(page, limit);//分页插件
        //获得example，查询信息
        MarketRoleExample example = new MarketRoleExample();
        MarketRoleExample.Criteria criteria = example.createCriteria();
        if (roleListBo.getName() != null && !"".equals(roleListBo.getName())) {
            criteria.andNameLike("%"+roleListBo.getName()+"%");
        }
        example.setOrderByClause(sort + " " + order);
        criteria.andDeletedEqualTo(false);
        List<MarketRole> marketRoleList = marketRoleMapper.selectByExample(example);
        PageInfo<MarketRole> rolePageInfo = new PageInfo<>(marketRoleList);
        int total = (int) rolePageInfo.getTotal();
        int pages = rolePageInfo.getPages();
        RoleListVo roleListVo = new RoleListVo(total,pages,limit,page,marketRoleList);
        return roleListVo;
    }

    @Override
    public MarketRole roleCreate(RoleCreateBo roleCreateBo) {
        MarketRole marketRole = new MarketRole();
        marketRole.setName(roleCreateBo.getName());
        marketRole.setDesc(roleCreateBo.getDesc());
        marketRole.setAddTime(new Date());
        marketRole.setUpdateTime(new Date());
        marketRole.setDeleted(true);
        marketRole.setDeleted(false);
        marketRoleMapper.insertSelective(marketRole);

//        Integer id = marketRole.getId();
//        MarketRole marketRole1 = marketRoleMapper.selectByPrimaryKey(id);
        return marketRole;
    }

    @Override
    public void updateRole(MarketRole marketRole) {
        marketRole.setUpdateTime(new Date());
        marketRoleMapper.updateByPrimaryKey(marketRole);
    }

    // 由于market_role表的name设置了UNIQUE，无法逻辑删除，只能真删
    @Transactional
    @Override
    public int deleteRole(MarketRole marketRole) {
        /*marketRole.setDeleted(true);
        marketRole.setEnabled(false);
        marketRoleMapper.updateByPrimaryKey(marketRole);*/
        Integer id = marketRole.getId();
        // 删除role_permissions_relation表中的角色授权记录
        rolePermissionsRelationMapper.deletePermissionsByRoleId(id);
        // 删除market_role表中的对应角色记录
        int delete = marketRoleMapper.deleteByPrimaryKey(id);
        if (delete == 1) {
            return 200;
        }
        return 404;
    }

    // 获取所有授权信息的List，以及当前role拥有的授权信息
    @Transactional
    @Override
    public RolePermissionsVO queryPermissions(Integer roleId) {
        // 所有授权信息的list
        // 第一步，查找所有 level=1 的授权信息，得到一个List，作为最外层List
        RolePermissionsExample example1 = new RolePermissionsExample();
        RolePermissionsExample.Criteria criteria1 = example1.createCriteria();
        criteria1.andTypeEqualTo(1).andPidEqualTo(0);
        List<RolePermissions> listL1 = rolePermissionsMapper.selectByExample(example1);
        // 第二步，遍历最外层List，根据id，查找所有 pid=外层id 的第二层记录，封装到外层的children
        for (RolePermissions permissionL1 : listL1) {
            RolePermissionsExample example2 = new RolePermissionsExample();
            RolePermissionsExample.Criteria criteria2 = example2.createCriteria();
            criteria2.andTypeEqualTo(2).andPidEqualTo(permissionL1.getIdPrimary());
            List<RolePermissions> listL2 = rolePermissionsMapper.selectByExample(example2);
            permissionL1.setChildren(listL2);
            // 第三步，遍历刚刚得到的第二层List，查找所有 pid=第二层id 的第三层记录，封装到第二层的children
            for (RolePermissions permissionL2 : listL2) {
                RolePermissionsExample example3 = new RolePermissionsExample();
                RolePermissionsExample.Criteria criteria3 = example3.createCriteria();
                criteria3.andTypeEqualTo(3).andPidEqualTo(permissionL2.getIdPrimary());
                List<RolePermissions> listL3 = rolePermissionsMapper.selectByExample(example3);
                permissionL2.setChildren(listL3);
            }
        }

        // 当前角色拥有的授权信息，查找关系表
        List<String> permissionsList = rolePermissionsRelationMapper.selectPermissionsByRoleId(roleId);

        RolePermissionsVO rolePermissionsVO = new RolePermissionsVO();
        rolePermissionsVO.setSystemPermissions(listL1);
        rolePermissionsVO.setAssignedPermissions(permissionsList);
        return rolePermissionsVO;
    }

    // 根据roleID，更新对应的授权信息
    // 返回code：200-更新成功，404-roleId不存在
    @Transactional
    @Override
    public int updateRolePermissions(RolePermissionBO rolePermissionBO) {
        @NotNull Integer roleId = rolePermissionBO.getRoleId();
        @NotNull List<String> permissions = rolePermissionBO.getPermissions();

        // 首先去market_role表里找，有没有这个角色，如果没有，返回404
        MarketRole role = marketRoleMapper.selectByPrimaryKey(roleId);
        if (role == null) {
            return 404;
        }
        // 有这个角色，去role_permissions_relation表里，删除该roleId对应的所有记录
        rolePermissionsRelationMapper.deletePermissionsByRoleId(roleId);
        // 然后添加List里的记录
        rolePermissionsRelationMapper.insertPermissionsByRoleId(roleId, permissions);
        return 200;
    }


}
